package com.ruoyi.web.controller.Planting;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.Goods.domain.Goods;
import com.ruoyi.Goods.service.IGoodsService;
import com.ruoyi.GoodsAttach.domain.GoodsAttach;
import com.ruoyi.Planting.domain.Planting;
import com.ruoyi.Planting.service.IPlantingService;
import com.ruoyi.School.domain.School;
import com.ruoyi.School.service.ISchoolService;
import com.ruoyi.common.config.Global;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateTools;
import com.ruoyi.common.utils.QiniuCloudUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.system.domain.SysDept;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.service.ISysDeptService;

/**
 * 轮播图 信息操作处理
 * 
 * @author ruoyi
 * @date 2019-08-06
 */
@Controller
@RequestMapping("/Planting/planting")
public class PlantingController extends BaseController
{
    private String prefix = "Planting/planting";
	
	@Autowired
	private IPlantingService plantingService;
	
	@Autowired
	private IGoodsService goodsService;
	
	@Autowired
    private ISysDeptService deptService;
	
	
	@RequiresPermissions("Planting:planting:view")
	@GetMapping()
	public String planting()
	{
	    return prefix + "/planting";
	}
	
	/**
	 * 查询轮播图列表
	 */
	@RequiresPermissions("Planting:planting:list")
	@PostMapping("/list")
	@ResponseBody
	public TableDataInfo list(Planting planting)
	{
		startPage();
        List<Planting> list = plantingService.selectPlantingList(planting);
		return getDataTable(list);
	}
	
	
	/**
	 * 导出轮播图列表
	 */
	@RequiresPermissions("Planting:planting:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(Planting planting)
    {
    	List<Planting> list = plantingService.selectPlantingList(planting);
        ExcelUtil<Planting> util = new ExcelUtil<Planting>(Planting.class);
        return util.exportExcel(list, "planting");
    }
	
	/**
	 * 新增轮播图
	 */
	@GetMapping("/add")
	public String add(ModelMap mmap)
	{
				
		SysDept example2 = new SysDept();
		List<SysDept> deptList = deptService.selectDeptList(example2);
		mmap.put("deptList", deptList);
		
	    return prefix + "/add";
	}
	
	/**
	 * 新增保存轮播图
	 * @throws IOException 
	 */
	@RequiresPermissions("Planting:planting:add")
	@Log(title = "轮播图", businessType = BusinessType.INSERT)
	@PostMapping("/add")
	@ResponseBody
	public AjaxResult addSave(Planting planting) throws IOException
	{		
		String imgData = planting.getImageUrl();
		if ((!StringUtils.isEmpty(imgData)) && (!imgData.startsWith("http"))) {
			imgData = imgData.substring(imgData.indexOf(",") + 1);
			byte[] bytes=Base64Utils.decodeFromString(imgData);
			String imageName = UUID.randomUUID().toString();
			QiniuCloudUtil qiniuUtil = new QiniuCloudUtil();
			try {
				String url = qiniuUtil.put64image(bytes, imageName);
				planting.setImageUrl(url);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		planting.setCreateDate(DateTools.getYMDhms());
		planting.setCreateBy(ShiroUtils.getSysUser().getUserName());
		return toAjax(plantingService.insertPlanting(planting));
	}

	/**
	 * 修改轮播图
	 */
	@GetMapping("/edit/{id}")
	public String edit(@PathVariable("id") Integer id, ModelMap mmap)
	{
		Planting planting = plantingService.selectPlantingById(id);		
		Goods example=new Goods();	
		example.setSchoolId(planting.getSchoolId().toString());
		List<Goods> goodsList=goodsService.selectGoodsList(example);		
		SysDept example2 = new SysDept();
		List<SysDept> deptList = deptService.selectDeptList(example2);
		mmap.put("deptList", deptList);
		mmap.put("planting", planting);
		mmap.put("goodsList", goodsList);
	    return prefix + "/edit";
	}
	
	/**
	 * 修改保存轮播图
	 * 
	 * @throws IOException
	 */
	@RequiresPermissions("Planting:planting:edit")
	@Log(title = "轮播图", businessType = BusinessType.UPDATE)
	@PostMapping("/edit")
	@ResponseBody
	public AjaxResult editSave(Planting planting) throws IOException {		
		String imgData = planting.getImageUrl();
		if ((!StringUtils.isEmpty(imgData)) && (!imgData.startsWith("http"))) {
			int id=planting.getId();
			Planting persist=plantingService.selectPlantingById(id);
			if(!StringUtils.isEmpty(persist.getImageUrl())){
				QiniuCloudUtil qiniuUtilforDelete = new QiniuCloudUtil();
				qiniuUtilforDelete.delete(persist.getImageUrl());
			}
			imgData = imgData.substring(imgData.indexOf(",") + 1);						
			byte[] bytes=Base64Utils.decodeFromString(imgData);
			String imageName = UUID.randomUUID().toString();
			QiniuCloudUtil qiniuUtil = new QiniuCloudUtil();
			try {
				String url = qiniuUtil.put64image(bytes, imageName);
				planting.setImageUrl(url);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		planting.setUpdateDate(DateTools.getYMDhms());
		planting.setUpdateBy(ShiroUtils.getSysUser().getUserName());
		return toAjax(plantingService.updatePlanting(planting));
	}
	
	@GetMapping("/searchGood")
	@ResponseBody
	public List<Goods> searchGood(String schoolId) {		
		Goods example=new Goods();
		example.setSchoolId(schoolId);
		List<Goods> goodsList=goodsService.selectGoodsList(example);		
		return goodsList;
	}
	
	/**
	 * 删除轮播图
	 */
	@RequiresPermissions("Planting:planting:remove")
	@Log(title = "轮播图", businessType = BusinessType.DELETE)
	@PostMapping( "/remove")
	@ResponseBody
	public AjaxResult remove(String ids)
	{		
		return toAjax(plantingService.deletePlantingByIds(ids));
	}
	
	@PostMapping("/changeStatus")
    @ResponseBody
    public AjaxResult changeStatus(Integer id)
    {
		Planting persist=plantingService.selectPlantingById(id);
		persist.setState(0);
        return toAjax(plantingService.updatePlanting(persist));
    }
	
	@PostMapping("/changeStatus2")
    @ResponseBody
    public AjaxResult changeStatus2(Integer id)
    {
		Planting persist=plantingService.selectPlantingById(id);
		persist.setState(1);
        return toAjax(plantingService.updatePlanting(persist));
    }
	
	public static boolean generateImage(String imgStr, String path)
			throws IOException {
		if (imgStr != null) {
			byte[] b = Base64Utils.decodeFromString(imgStr);
			for (int i = 0; i < b.length; ++i) {
				if (b[i] < 0) {
					b[i] += 256;
				}
			}
			OutputStream out = new FileOutputStream(path);
			out.write(b);
			out.flush();
			out.close();
			return true;
		}
		return false;
	}
	
	
}
